#include <func.h>

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,3);
    int socketFd;
    //初始化一个socket，有一个缓冲区
    socketFd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socketFd,-1,"socket");
    printf("client : socketFd=%d\n",socketFd);
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_port=htons(atoi(argv[2]));
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    int ret;
    ret=connect(socketFd,(struct sockaddr*)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"connect");
    printf("client : connected\n");
    
    char buf[1000] = {0};
    //接收文件名
    int dataLen = 0;
    recv(socketFd,&dataLen,sizeof(int),0);// length of file name 
    recv(socketFd,buf,dataLen,0);// file name 

    int fd;
    int i = 1;
    // 这里实现如果有重名的文件，则在新建文件名后边加递增的数字，直到没有重名
    while(-1 == (fd = open(buf,O_WRONLY|O_CREAT,0666)))
    {
        sprintf(buf,"%s%d",buf,i++);
    }
    
    //接收文件内容
    //得到数据长度
    while(1)
    {
        recv(socketFd,&dataLen,sizeof(int),MSG_WAITALL);
        if(dataLen)
        {
            recv(socketFd,buf,dataLen,MSG_WAITALL);
            write(fd,buf,dataLen);
        }else{
            break;
        }
    }
    

    close(socketFd);
    return 0;
}
